/**
 * @Title: WechatLoginController.java
 * @Package com.leesche.zcsp.node.web.controller.wechat
 * @Description:()
 * @author dennies yang
 * @date 2016年10月12日 下午7:43:38
 * @version V1.0
 */
package com.leesche.zcsp.node.web.controller.wechat.login;

import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.pay.wecha.data.Oauth2To;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.utils.web.validation.Regex;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.LoginTemplate;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysModuleCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Account;
import com.leesche.zcsp.node.web.vo.Principal;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Map;

/**
 * @author dennies yang
 * @version V1.0
 * @Title: WechatLoginController.java
 * @Package com.leesche.zcsp.node.web.controller.wechat
 * @Description:()
 * @date 2016年10月12日 下午7:43:38
 */
@Controller
@RequestMapping(value = "/wechat/login")
public class WechatLoginController extends LoginTemplate {
	private static final Logger logger = Logger
			.getLogger(WechatLoginController.class);
	
	public final static String CURRENT_SITENAME = "/wechat/login/";

	//private final static String GOTOINDEX = "wechat/income/accounts/mainView";
	private final static String GOTOINDEX = "/wechat/income/accounts/mainView";
	private final static String GOTOLOGIN = "wechat/login/login";

	private final static String USER_MAINVIEW = "wechat/login/user/mainView";
	private final static String FORGET_MAINVIEAW = "wechat/login/Forget/mainView";

	//机修角色界面
	private final static String MACHINE_REPAIR_VIEW = "/wechat/operate/device/listView";
	//财务兼机修界面
	private final static String FINANCE_MACHINE_VIEW = "/wechat/income/accounts/mainView";
/*
	@Autowired
	private NetService netService;*/

	@Autowired
	private PrivilegeService privilegeService;

	@RequestMapping(value = "signIn", method = RequestMethod.GET)
	public String login(String redirectUrl, HttpServletRequest request) {
			return GOTOLOGIN;
	}

	/***
	 * @param @param request
	 * @param @return
	 * @return String
	 * @throws
	 * @Title: gotoIndex
	 * @Description: TODO(微信进入时跳转到登录界面)
	 */
	@RequestMapping(value = "gotoSignIn", method = RequestMethod.GET)
	public String gotoIndex(String redirectUrl, HttpServletRequest request) {

		StringBuffer url = new StringBuffer();
		url.append(request.getScheme());
		url.append("://");
		url.append(request.getServerName());
		url.append("/");
		url.append(Constants.SITE_NAME);
		url.append(CURRENT_SITENAME);
		url.append("index");
		if (StringUtils.isNotBlank(redirectUrl)) {
			url.append("?redirectUrl=" + redirectUrl);
		}
		logger.info(url.toString());
		return "redirect:" + wechatService.getWechatRedirectUrl(url.toString());
	}

	/**
	 * 
	 * @Title: index
	 * @Description: TODO(登录界面 通过微信网页授权)
	 * @param @param code
	 * @param @param request
	 * @param @param response
	 * @param @param model
	 * @param @return
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(String code, String redirectUrl,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		Message<Oauth2To> message = wechatService.getOauth(code);
	//	Oauth2To oauth2To = new Oauth2To();
	//	oauth2To.setOpenid("o616as_W_4LV14_zXUoQkZjmhEk4");
	//	Message<Oauth2To> message = Message.success(oauth2To, null);
		if (Message.isSuccess(message.getType())) {
			Cookie cookie = new Cookie("openid", message.getContent()
					.getOpenid());
			cookie.setMaxAge(60 * 60);
			cookie.setPath("/");
			response.addCookie(cookie);
			logger.info("OpenID=" + message.getContent().getOpenid());
			QuerySysUserCondition conditon = new QuerySysUserCondition();
			conditon.setOpenid(message.getContent().getOpenid());
			SysUserDto loginUser = sysUserService.findByCondition(conditon);
			if (loginUser != null) {
				String principalName = loginUser.getBusinessno() != null ? loginUser
						.getBusinessno() : loginUser.getUsername();

				Principal principal = new Principal(loginUser.getUserid(),
						loginUser.getPuserid(), principalName,
						loginUser.getBusinessno(), loginUser.getNtype(),
						loginUser.getOpenid(), Constants.MODULE_TYPE_WECHAT,loginUser.getShortcode());

				QuerySysModuleCondition querySysModuleCondition = new QuerySysModuleCondition();
				querySysModuleCondition.setnType(Constants.MODULE_TYPE_WECHAT);
				querySysModuleCondition.setUserId(principal.getUserid());
				principal.setModuleIds(sysModuleService
						.findModuleIDbyUserID(querySysModuleCondition));

				request.getSession().setAttribute(Constants.LOGIN_CURRENT_USER,
						principal);
				logger.info("redirectUrl:"+redirectUrl);
				if (StringUtils.isNotEmpty(redirectUrl)) {
					return "redirectUrl:" + redirectUrl;

				}
				logger.info("redirectUrl GOTOINDEX:"+GOTOINDEX);

				String goView;
				switch (loginUser.getNtype()){
					//财务
					case 5:
						goView = FINANCE_MACHINE_VIEW;
						break;
					//机修
					case 6 :
						goView = MACHINE_REPAIR_VIEW;
						break;
					//财务兼机修
					case 7:
						goView = FINANCE_MACHINE_VIEW;
						break;
					default:
						goView = GOTOINDEX;
						break;
				}

				return "redirect:" +  goView;
			}
		}

		return GOTOLOGIN;
	}

	@ResponseBody
	@RequestMapping(value = "signin", method = RequestMethod.POST)
	public Map<String, Object> login(HttpSession session, Account accout) {
		try {

			if (!SessionManager.getSessionAttribute(Constants.LOGIN_CODE).equals(accout.getVildCode())) {
				return WebResult.failure("验证码输入错误").toMap();
			}

			return super.userLogin(accout, Constants.MODULE_TYPE_WECHAT);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return WebResult.failure(e).toMap();
		}

	}
	
	/**
	 * 
	 * @Title: listView @Description: TODO(打开找回密码之验证用户是否存在) @param @param model @param @return @return
	 *         String @throws
	 */
	@RequestMapping(value = "showView", method = RequestMethod.GET)
	public String showView(Model model) {
		return USER_MAINVIEW;
	}

	/***
	 * 
	 * @Title: listView @Description: TODO(打开找回密码界面值更改密码是否存在) @param @param
	 *         model @param @return @return String @throws
	 */
	@RequestMapping(value = "forget", method = RequestMethod.GET)
	public String forget(Long userId, ModelMap model) {
		model.put("userId", userId);
		return FORGET_MAINVIEAW;
	}
	
	/**
	 * 
	 * @Title: validUser
	 * @Description: TODO(验证用户名是否存在)
	 * @param @param username
	 * @param @param session
	 * @param @return
	 * @return Map<String,Object>
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "validUser", method = RequestMethod.POST)
	public Map<String, Object> validUser(String username, HttpSession session) {
		// 获取用户信息
		/**
		 * 验证当前用户使用的是手机还是邮箱或者是用户登录
		 */
		SysUser sysUser = new SysUser();

		if (Regex.isEmail(username)) {

			sysUser.setEmail(username);

		} else if (Regex.isMobile(username)) {

			sysUser.setMobile(username);

		} else {

			sysUser.setUsername(username);

		}

		// 根据用户的账户名获取用户信息
		sysUser = sysUserService.findUserByUsername(sysUser);

		// 判断用户是否存在
		if (sysUser == null) {
			return WebResult.failure("用户名不存在,请重新输入!").toMap();
		} else {
			return WebResult.success()
					.info(String.valueOf(sysUser.getUserid())).toMap();
		}

	}

	/**
	 * 
	 * @Title: editPassword
	 * @Description: TODO()
	 * @param @param userId
	 * @param @param password
	 * @param @param npassword
	 * @param @param validCode
	 * @param @param session
	 * @param @return
	 * @return Map<String,Object>
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "ep", method = RequestMethod.POST)
	public Map<String, Object> editPassword(Long userId, String password,
			String npassword, String validCode, HttpSession session) {
		// 判断两次密码是否一致
		if (!password.equals(npassword)) {
			return WebResult.failure("输入两次密码不一致!").toMap();
		}
		SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
		// 判断用户是否存在
		if (sysUser == null) {
			return WebResult.failure("用户不存在,请重新输入!").toMap();
		}
		// 判断验证是否有效
		String smsCode = (String) session
				.getAttribute(Constants.MOBILE_SMS_CODE);
		if (!validCode.equals(smsCode)) {
			return WebResult.failure("验证码输入有误，请重新输入!").toMap();
		}

		try {
			// 执行修改密码操作
			sysUser.setPassword(QEncodeUtil.md5Encrypt(password));

			sysUserService.changePassword(sysUser);
			return WebResult.success().info("修改密码成功").toMap();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return WebResult.failure(e).toMap();
		}

	}

	/**
	 * 用户通过不同角色登录之后跳转页面
	 * @return
	 */
	@RequestMapping(value = "/goView", method = RequestMethod.GET)
	public String goView(){
		Integer userRoleType = privilegeService.getCurrentPrincipal().getNtype();
		String goView;

		switch (userRoleType){
			//财务
			case 5:
				goView = FINANCE_MACHINE_VIEW;
				break;
			//机修
			case 6 :
				goView = MACHINE_REPAIR_VIEW;
				break;
			//财务兼机修
			case 7:
				goView = FINANCE_MACHINE_VIEW;
				break;
			default:
				goView = GOTOINDEX;
				break;
		}

		return "redirect:" +  goView;
	}
	
}
